package com.ai.bitcoin.helper;

import com.ai.bitcoin.constant.JwtConstant;
import com.ai.bitcoin.exception.BusinessException;
import com.ai.bitcoin.jpa.entity.BccUser;
import com.ai.bitcoin.util.JacksonUtils;
import com.ai.bitcoin.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 解析用户token
 * Created by gulj on 2018/6/11.
 */
@Component
@Slf4j
public class JwtParseTokenHelper {


    @Autowired
    private JwtUtil jwtUtil;


    /**
     * 解析用户token
     *
     * @param token
     * @return
     * @throws BusinessException
     */
    public BccUser parseToken(String token) throws BusinessException {
        Claims claims = null;
        try {
            claims = jwtUtil.parseJWT(token);
            BccUser user = JacksonUtils.fromJson(claims.getSubject(), BccUser.class);
            if (log.isDebugEnabled()) {
                log.debug(user.toString());
            }
            if (user == null || user.getSymbol() == null) {
                log.error("token exception");
                throw new BusinessException(JwtConstant.RESCODE_NOLOGIN, "token异常");
            }
            return user;
        } catch (Exception e) {
            log.error("验签解密出错,{}", e);
            throw new BusinessException(JwtConstant.RESCODE_NOLOGIN, "验签解析异常，请重新登录");
        }
    }

}
